<template>
  <el-card shadow="hover" style="margin: 10px">
    <div slot="header" v-if="!options.hideSearch && !options.layout">
      <!-- 查询过滤 -->
      <tableFilter
        v-bind="$attrs"
        v-on="$listeners"
        :options="options.columns"
        @handleSearch="handleSearch"
      >
      </tableFilter>
    </div>
    <!-- card body -->

    <el-row :gutter="24">
      <el-col :span="3" :offset="0" v-if="options.layout === 'vertical'">
        <tableFilter
          v-bind="$attrs"
          v-on="$listeners"
          :options="options.columns"
          @handleSearch="handleSearch"
        >
        </tableFilter>
      </el-col>
      <el-col :span="options.layout ? 21 : 24" :offset="0">
        <vxe-toolbar
          ref="toolbarRef"
          custom
          print
          :import="options.import || false"
        >
          <template #buttons>
            <el-button
              type="info"
              @click="handleExport"
              v-if="!options.hideExport"
              icon="el-icon-printer"
              >导出数据</el-button
            >
            <slot name="btn"></slot>
          </template>
        </vxe-toolbar>

        <vxe-table
          ref="table"
          header-row-class-name="vxe_table_header"
          size="mini"
          @cell-click="cellClickEvent"
          @radio-change="radioChangeEvent"
          @checkbox-all="selectAllEvent"
          @checkbox-change="selectChangeEvent"
          :border="options.border || false"
          :loading="loading"
          :id="options.id || null"
          :height="options.height || 600"
          :data="tableData"
          :column-config="{ useKey: true, resizable: true }"
          :show-overflow="options.showOverflow || false"
          :cell-config="{ ...options.cellConfig }"
          :import-config="{
            types: ['xlsx'],
            mode: 'covering',
            remote: true, //是否服务端导入
            importMethod: ({ file, options }) =>
              this.tableImport(file, options),
          }"
          :row-config="{
            useKey: true,
            isHover: true,
            isCurrent: true,
            ...options.rowConfig,
          }"
          :current-row-config="{
            isFollowSelected: true,
          }"
          :custom-config="{ storage: true }"
          :print-config="{}"
          :export-config="{}"
          :keyboard-config="{ isArrow: true }"
          :show-footer="options.showFooter || false"
          :footer-method="options.footerMethod || null"
          :tree-config="options.treeConfig || null"
          :edit-rules="options.editRules || null"
          :edit-config="options.editConfig || null"
        >
          <vxe-column type="radio" width="60" v-if="options.radio">
            <template #header>
              <vxe-button
                mode="text"
                @click="clearRadioRowEevnt"
                :disabled="!selectRow"
                >取消</vxe-button
              >
            </template>
          </vxe-column>
          <vxe-column type="checkbox" width="60" v-if="options.checkbox">
          </vxe-column>
          <vxe-column
            v-for="item in options.columns"
            :type="item.type || null"
            :key="item.field"
            :title="item.title"
            :field="item.field"
            :width="item.width || null"
            :title-prefix="item.tips || null"
            :align="item.align || 'center'"
            :fixed="item.fixed || null"
            :formatter="item.formatter || null"
            :sortable="item.sortable || false"
            show-overflow
            show-header-overflow
            :tree-node="item.treeNode || null"
            :edit-render="item.editRender || null"
          >
            <template v-if="item.slot" #default="{ row, seq }">
              <slot :name="item.slot" :row="row" :index="seq - 1"></slot>
            </template>
          </vxe-column>
          <vxe-column
            fixed="right"
            title="操作"
            :width="options.btnWidth || 200"
            :align="options.btnAlign || 'center'"
            field="btn"
            v-if="options.btn"
          >
            <template #default="{ row, seq }">
              <el-button
                v-for="btn in options.btn"
                :key="btn.title"
                style="margin: 0 10px"
                plain
                :type="btn.type || 'primary'"
                v-show="!btn.show || btn.show(row)"
                @click.stop="handleTableBtn(btn.handleName, row, seq)"
                >{{ btn.title }}</el-button
              >
            </template>
          </vxe-column>
        </vxe-table>
        <vxe-pager
          v-if="!options.hidePage"
          style="margin-top: 8px"
          :loading="loading"
          :current-page="queryparams.pageIndex"
          :page-size="
            options.pageSize ? options.pageSize : queryparams.pageSize
          "
          :total="total"
          :layouts="[
            'PrevPage',
            'JumpNumber',
            'NextPage',
            'FullJump',
            'Sizes',
            'Total',
          ]"
          @page-change="handlePageChange"
        >
        </vxe-pager>
      </el-col>
    </el-row>
  </el-card>
</template>

<script>
import { importXlsx } from "@/utils";
import { Message, Notification } from "element-ui";
import { options } from "runjs";

export default {
  props: ["options"],
  data() {
    return {
      selectRow: null,
      tableData: [],
      loading: false,
      form: {}, //外部查询参数
      total: 0,
      queryparams: {
        pageIndex: 1,
        pageSize: this.options.pageSize ? this.options.pageSize : 15,
      },
    };
  },
  created() {
    this.$nextTick(() => {
      this.$refs.table.connect(this.$refs.toolbarRef);
    });
  },
  mounted() {
    if (!this.options.disSearch) {
      this.initData();
    }
    const $table = this.$refs.table;
    const $toolbar = this.$refs.toolbarRef;
    if ($table && $toolbar) {
      $table.connect($toolbar);
    }
  },
  methods: {
    initData() {
      const tabeleParams = Object.assign(
        this.queryparams,
        this.form,
        this.options.fixedParams
      );

      // console.log(tabeleParams, "查询参数----");
      if (this.options.apiFn) {
        this.loading = true;
        this.options
          .apiFn({ ...tabeleParams })
          .then((res) => {
            this.loading = false;
            if (!res.status) {
              this.$emit("init");
              if (res.content) {
                this.tableData = res.content;
              } else {
                this.tableData = [];
              }
              this.total = res.total ? res.total : res.data.length;
            }
          })
          .catch((err) => {
            this.loading = false;
          });
      }
    },
    // 单元格点击
    cellClickEvent({ column, row }) {
      this.$emit("clickCell", column.title, row);
      // console.log(column.title, row, "单元格点击事件");
    },
    // 单选
    radioChangeEvent({ row }) {
      this.selectRow = row;
      this.$emit("radio", row);
    },
    clearRadioRowEevnt() {
      this.selectRow = null;
      this.$refs.table.clearRadioRow();
    },
    // 多选
    selectAllEvent({ checked }) {
      const records = this.$refs.table.getCheckboxRecords();
      this.$emit("checked", this.$refs.table.getCheckboxRecords());
      console.log(checked ? "所有勾选事件" : "所有取消事件", records);
    },
    selectChangeEvent({ checked }) {
      const records = this.$refs.table.getCheckboxRecords();
      this.$emit("checked", this.$refs.table.getCheckboxRecords());
      console.log(checked ? "勾选事件" : "取消事件", records);
    },
    handleExport() {
      this.$refs.table.openExport();
    },
    handlePageChange({ currentPage, pageSize }) {
      console.log({ currentPage, pageSize });
      this.queryparams.pageIndex = currentPage;
      this.queryparams.pageSize = pageSize;
      this.initData();
    },
    handleSearch(params) {
      this.form = params;
      this.queryparams.pageIndex = 1;
      this.initData();
    },
    // 事件
    handleTableBtn(name, row, index) {
      this.$emit("handleTableBtn", name, row, index - 1);
    },
    tableImport(file, options) {
      importXlsx(file, this.options.importKeys, async (data) => {
        console.log(data, "xxxxxxxxxxxxxxx");
        const res = await this.options.apiImport({
          lights: JSON.stringify(data),
        });
        if (!res.status) {
          if (res.content.failCount) {
            Notification({
              title: "提示",
              message: `${res.content.failCount}条导入失败,${res.content.failNames}`,
              type: "error",
            });
          }
          Message.success("成功导入" + res.content.successCount + "条数据");
        }
        this.handleSearch();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.a {
  text-align: center;
}
</style>
